package com.ctgu.tengyun.manager;

import com.ctgu.tengyun.domain.SysRole;
import com.ctgu.tengyun.service.role.SysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by liaoweizhi on 2019/8/13.
 */
public class UserRoleScheduleManager {

    private static final Logger logger = LoggerFactory.getLogger(UserRoleScheduleManager.class);

    private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

    @Autowired
    private SysRoleService sysRoleService;

    public static List<SysRole> allRoleList = new ArrayList<>();
    public static Map<Integer, SysRole> roleMap = new HashMap<>();
    private int runIntervalSeconds = 300;

    public void stop() {
        if (service != null) {
            logger.info("UserRoleScheduleManager stop");
            service.shutdownNow();
        }
    }

    public void init() {
        try {
            fillData();
        } catch (RuntimeException ex) {
            logger.error("fill data error.", ex);
        }
        service.scheduleWithFixedDelay(() -> {
            try {
                fillData();
            } catch (RuntimeException ex) {
                logger.error("fill data error.", ex);
            }
        }, 0, getRunIntervalSeconds(), TimeUnit.SECONDS);
        logger.info("init UserRoleScheduleManager success...");
    }

    public void fillData() {
        List<SysRole> roleList = sysRoleService.selectAll();
        logger.info("sync UserRoleScheduleManager,role count:" + roleList.size());

        Map<Integer, SysRole> tempRoleMap = new HashMap<>(roleList.size());
        roleList.forEach(item -> {
            tempRoleMap.put(item.getId(), item);
        });

        allRoleList = roleList;
        roleMap = tempRoleMap;
    }

    public void setRunIntervalSeconds(int runIntervalSeconds) {
        this.runIntervalSeconds = runIntervalSeconds;
    }

    public int getRunIntervalSeconds() {
        return runIntervalSeconds;
    }

    public static SysRole getRoleById(Integer roleId) {
        return roleMap.get(roleId);
    }

}
